package k8s

import (
	"context"
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"strings"
)

func replaceString(s string) string {
	newContent := strings.ReplaceAll(s, "online-redis", "online.redis.huadaocart.corp")
	newContent = strings.ReplaceAll(newContent, "192.168.1.171:31103", "online.redis.huadaocart.corp")
	newContent = strings.ReplaceAll(newContent, "online-mongodb", "online.mongodb.huadaocart.corp")
	newContent = strings.ReplaceAll(newContent, "192.168.1.171:31203", "online.mongodb.huadaocart.corp")
	newContent = strings.ReplaceAll(newContent, "online-rabbitmq", "online.rabbitmq.huadaocart.corp")
	newContent = strings.ReplaceAll(newContent, "192.168.1.171:31303", "online.rabbitmq.huadaocart.corp")
	newContent = strings.ReplaceAll(newContent, "online-minio", "online.minio.huadaocart.corp")
	newContent = strings.ReplaceAll(newContent, "192.168.1.171:31403", "online.minio.huadaocart.corp")

	newContent = strings.ReplaceAll(newContent, "online.mssql.huadaopharma", "online.mssql.huadaocart.corp")

	return newContent
}

func K8sConfig() {
	// 加载 Kubernetes 配置文件
	config, err := clientcmd.BuildConfigFromFlags("", "C:\\Users\\Administrator\\.kube\\config")
	if err != nil {
		panic(err)
	}

	// 创建 Kubernetes 客户端
	client, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err)
	}

	// 获取 online 命名空间下的所有 ConfigMap
	options := metav1.ListOptions{}
	configMaps, err := client.CoreV1().ConfigMaps("online").List(context.TODO(), options)
	if err != nil {
		panic(err)
	}

	// 轮流修改 ConfigMap 的值
	for _, configMap := range configMaps.Items {
		//fmt.Printf("ConfigMap %s:\n", configMap.Name)
		if configMap.Name == "bpm-config" {
			for key, value := range configMap.Data {
				if key == "appsettings.Online.json" || key == "nlog.Online.config" {
					newValue := replaceString(value)
					configMap.Data[key] = newValue
					fmt.Printf("  %s: %s\n", key, newValue)
				}
			}

			// 更新 ConfigMap
			_, err := client.CoreV1().ConfigMaps("online").Update(context.TODO(), &configMap, metav1.UpdateOptions{})
			if err != nil {
				panic(err)
			}

			fmt.Println(configMap.Name + "更新完成")

		}
	}
}
